package com.tablefood.dao.Impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.tablefood.dao.CategoryDao;
import com.tablefood.domain.ShopCategory;


public class CategoryDaoImpl implements CategoryDao {

	@Resource
	private SessionFactory sessionFactory; 
	
	@Override
	public List<ShopCategory> getAllCategory() {
		 
		String state = "1" ;
		String hql = "from ShopCategory u where u.state = ?"; // 查询语句
	 
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, state);
		List<ShopCategory> list = query.list();
		 
		return list;
	}

	@Override
	public boolean delCategory(Long cateid) {
		 
		ShopCategory category = (ShopCategory) sessionFactory.getCurrentSession().load(ShopCategory.class, cateid);
		category.setState("0");
		return true;
	}

	@Override
	public ShopCategory getCategoryByCateId(Long cateid) {
		String hql = "FROM ShopCategory AS u WHERE  u.state = '1' and u.cateid = ?"; 
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setLong(0, cateid);  
		ShopCategory category = (ShopCategory) query.uniqueResult();   
	 
		if (category != null) {
			return category;
		}else{
			return null;
		}
	}

	@Override
	public boolean addCategory(ShopCategory category) {
	 
		try {
			sessionFactory.getCurrentSession().save(category);
		}catch(Exception e) { 
			e.printStackTrace(); 
			return false;
		}  
		return true;
	}

	@Override
	public boolean checkCategoryTitle(String title) {
		String hql = "FROM ShopCategory AS u WHERE  u.state = '1' and u.title = ?"; 
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, title);  
		List<ShopCategory> category = query.list();
	 
		if (category.size() > 0) {
			return true;
		}else{
			return false;
		}
	}

	@Override
	public boolean updateCategory(ShopCategory category) {
	 
		try {
			sessionFactory.getCurrentSession().saveOrUpdate(category);
		}catch(Exception e) { 
			e.printStackTrace(); 
			return false;
		} 
		return true;
	}

	@Override
	public boolean hasChild(Long cateid) {
		String hql = "FROM ShopCategory AS u WHERE  u.state = '1' and u.parentid = ?"; 
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setLong(0, cateid);  
		List<ShopCategory> category = query.list();
	 
		if (category.size() > 0) {
			return true;
		}else{
			return false;
		}
	}

	@Override
	public boolean hasParent(Long cateid) {
		String hql = "FROM ShopCategory AS u WHERE  u.state = '1' and u.cateid = ?"; 
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setLong(0, cateid);  
		List<ShopCategory> category = query.list();
	 
		if (category.size() > 0) {
			return true;
		}else{
			return false;
		}
	}

}

